package com.hamizhong.iflowers.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.hamizhong.iflowers.web.base.MyBaseAction;

public class AjaxAddToShoppingCartAction extends MyBaseAction {

	@Override
	protected String doRequest() {
		logger.info("----------------- Hello AjaxAddToShoppingCartAction -----------------");

		String goodsId = getRQ().getParameter("goodsId");
		
		HttpServletRequest request = getRQ();
		PrintWriter pw = null;
		try {
			pw = getPW();
		} catch (IOException e) {
			e.printStackTrace();
			pw.write("failedOther");
		}
		
		String cartGoodsStr = "";
		String newCartGoodsStr = "";
		String[] arr0;//长度为2，用于暂时存放key和value
		String[] arr1;//购物车中已经添加的个数（用“_”分隔）
		String[] arr2;//存放商品的key
		String[] arr3;//存放商品的数量
		//key和value之间通过“-”分隔
		
		try {
			Cookie[] cookie = request.getCookies();
			if(cookie != null) {
				for(int i=0;i<cookie.length;i++) {
					String res = cookie[i].getName();
					if(res.equals("iFlowers_Shopping_Cart")) {
						cartGoodsStr = cookie[i].getValue();
						break;
					}
				}
			}
			if(!cartGoodsStr.equals("")) {
				arr1 = cartGoodsStr.split("_");
				arr2 = new String[arr1.length];
				arr3 = new String[arr1.length];

				for(int i=0;i<arr1.length;i++) {
					arr0 = new String[2];
					arr0 = arr1[i].split("-");
					arr2[i] = arr0[0];
					arr3[i] = arr0[1];
				}
				for(int i=0;i<arr2.length;i++) {
					if(arr2[i].equals(String.valueOf(goodsId))) {
						pw.write("failed");
						return null;
					}
				}
				for(int i=0;i<arr2.length;i++) {
					newCartGoodsStr += arr2[i]+"-"+arr3[i]+"_";
				}
				newCartGoodsStr += goodsId+"-"+"1"+"_";
			}else {
				newCartGoodsStr += goodsId+"-"+"1"+"_";
			}
			logger.info("【cookie】newCartGoodsStr:"+newCartGoodsStr);
			pw.write(newCartGoodsStr);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			pw.write("failedOther");
			return null;
		}
	}


}
